<?php
/**
* Update logs
* 10/01/2010        immanuel192     First create view_page based on class::show
* Oct 14, 2010      immanuel192     Fix bug exponent flow set cause loop forever
* Feb 11, 2011      trungdt         Remove long date time, make it to short date time to LIKE hoithanh.com style
* Feb 12, 20111     trungdt         Set page title
* 
*/
	global $db, $user;

	$config = $db->selectObject('newsmodule_config',"location_data='".serialize($loc)."'");
	if (empty($config)) {
		$config->sortorder = 'DESC';
		$config->sortfield = 'posted';
		$config->item_limit = 10;
		$config->enable_pagination = 1;            
		$config->enable_rss = false;
		$config->group_by_tags = false;
		$config->pull_rss = 0;
		$config->aggregate = array();
		$config->collections = serialize(array());
	}

	$locsql = "(location_data='".serialize($loc)."'";
	if (!empty($config->aggregate)) {
		$locations = unserialize($config->aggregate);
		foreach ($locations as $source) {
			$tmploc = null;
			$tmploc->mod = 'newsmodule';
			$tmploc->src = $source;
			$tmploc->int = '';
			$locsql .= " OR location_data='".serialize($tmploc)."'";
		}
	}
	$locsql .= ')';
	
	// 10/01/2010 - immanuel192 - get module title - begin
	// get module title
	// because if the client switch page, so, that is the action and exponent does not transfer $title and $views        
	$temp=$db->selectObject("container","internal = '" . serialize($loc) . "'");
	if ($temp)
	{
		$title=$temp->title;
		$view=$temp->view;
	}
	else
	{
		$title="";
		$view="Summary"; // default viewer for news module. hehe
	}
	// 10/01/2010 - immanuel192 - get module title - end
	
	// Check permissions for AP link
	$canviewapproval = false;
	if ($user) $canviewapproval = exponent_permissions_check('approve',$loc) || exponent_permissions_check('manage_approval',$loc);
	if (!$canviewapproval) { // still not able to view
		foreach($db->selectObjects('newsitem', $locsql." AND (publish = 0 or publish <= " . time() . ") AND (unpublish = 0 or unpublish > " . time() . ') AND approved != 0') as $post) {
			if ($user && $user->id == $post->poster) {
				$canviewapproval = true;
				break;
			}
		}
	}

	if ($config->group_by_tags == true) {    
		$view = "_group_by_tags";    
	} 

	$template = new template('newsmodule',$view,$loc);

	$template->assign('moduletitle',$title);
	$template->register_permissions(
	array('administrate','configure','add_item','delete_item','edit_item','manage_approval','view_unpublished'),
	$loc
	);

	//If rss is enabled tell the view to show the RSS button    
	if (!isset($config->enable_rss)) {$config->enable_rss = 0;}
	$template->assign('enable_rss', $config->enable_rss);

	//Get the tags that have been selected to be shown in the grouped by tag views
	if (isset($config->show_tags)) {
		$available_tags = unserialize($config->show_tags);
	} else {
		$available_tags = array();
	}
	
	// pagination by item_limit
	$total = $db->countObjects('newsitem', $locsql." AND (publish = 0 or publish <= " . 
	time() . ") AND (unpublish = 0 or unpublish > " . time() . ") AND approved != 0");
	
	$max_item=$config->item_limit; 
	
	// page split
	// cal how many posts
	$page_count=floor($total / $max_item);
	if ($total % $max_item != 0)
		$page_count++;

	// get page
	$page=1;
	if (isset($_REQUEST['page']))  $page=intval($_REQUEST['page']);
	if (($page<1) || ($page>$page_count)) $page=1;
	$start_pos=($page-1)*$max_item;
	

	if($config->enable_pagination == 0) {
		//Get the news items.
		$news = $db->selectObjects('newsitem',$locsql." AND (publish = 0 or publish <= " . time() . ') AND (unpublish = 0 or unpublish > ' . time() . ') AND approved != 0 ORDER BY '.$config->sortfield.' ' . $config->sortorder ); //. $db->limit($config->item_limit,0));
	} else {                
		$news = $db->selectObjects('newsitem',$locsql." AND (publish = 0 or publish <= " . 
		time() . ') AND (unpublish = 0 or unpublish > ' . time() . ') AND approved != 0 ORDER BY '.
		$config->sortfield.' ' . $config->sortorder . $db->limit($config->item_limit,$start_pos));
	}
	// end of pagination

	$featured = $db->selectObjects('newsitem',$locsql." AND is_featured AND (publish = 0 or publish <= " . time() . ') AND (unpublish = 0 or unpublish > ' . time() . ') AND approved != 0 ORDER BY '.$config->sortfield.' ' . $config->sortorder ); //. $db->limit($config->item_limit,0));

	for ($i = 0; $i < count($news); $i++) {
		$news[$i]->real_posted = ($news[$i]->publish != 0 ? $news[$i]->publish : $news[$i]->posted);
		$nloc = exponent_core_makeLocation($loc->mod,$loc->src,$news[$i]->id);
		$news[$i]->permissions = array(
		'edit_item'=>((exponent_permissions_check('edit_item',$loc) || exponent_permissions_check('edit_item',$nloc)) ? 1 : 0),
		'delete_item'=>((exponent_permissions_check('delete_item',$loc) || exponent_permissions_check('delete_item',$nloc)) ? 1 : 0),
		'administrate'=>((exponent_permissions_check('administrate',$loc) || exponent_permissions_check('administrate',$nloc)) ? 1 : 0)
		);

		//Get the tags for this newsitem
		$selected_tags = array();
		$tag_ids = unserialize($news[$i]->tags);
		if(is_array($tag_ids)) {$selected_tags = $db->selectObjectsInArray('tags', $tag_ids, 'name');}
		$news[$i]->tags = $selected_tags;

		//If this module was configured to group the newsitems by tags, then we need to change the data array a bit
		if ($config->group_by_tags == true) {
			$grouped_news = array();
			foreach($news[$i]->tags as $tag) {
				if (in_array($tag->id, $available_tags) || count($available_tags) == 0) {
					if (!isset($grouped_news[$tag->name])) { $grouped_news[$tag->name] = array();} 
					array_push($grouped_news[$tag->name],$news[$i]);
				}
			}
		}    
	}

	foreach ($news as $item){
		// Mar 19, 2012 - fix bug wrong src when include news from other module
		$cur_loc = unserialize($item->location_data);
		$item->cur_loc = $cur_loc->src;
		// 10/01/2010 - immanuel192 - enable SEO support - begin
		$item->seo_tag_name=_to_vietnamese_with_nomark($item->title);
		// 10/01/2010 - immanuel192 - enable SEO support - end
		$file = $db->selectObject("file","id=".$item->file_id);
		if(!empty($file)){
			$item->image = $file->directory.'/'.$file->filename;
		}
		else
			$item->image = "";
		// Feb 11, 2011 - trungdt - Remove datetime - begin
		$date_time=0;
		if ($item->edited == 0)
			$date_time=$item->real_posted;
		else
			$date_time=$item->edited;
		$datetime = date('d/m/Y', $date_time);    
		//for date
		/*$date_translate = exponent_lang_loadFile('subsystems/forms/controls/yuicalendarcontrol.php');
		$datetime = date('l, F d, o g:i a', $date_time);
		// If the language is english, use the default language of yui calendar
		if (USE_LANG != 'eng_US') {
			// Translate days of the week
			// thứ
			$datetime=$date_translate[strtolower(substr(date('l',$date_time),0,2))].", ";
			// ngày
			$datetime.=date('d',$date_time)." ";
			// tháng
			$datetime.=$date_translate[strtolower(date('F',$date_time))]." ";
			// năm
			$datetime.=date('o',$date_time)."; ";
			$datetime.=date('g:i',$date_time)." ";
			// am - pm
			$datetime.=$date_translate[strtolower(date('a',$date_time))];
		}*/
		$item->datetime=$datetime;
		// Feb 11, 2011 - trungdt - Remove datetime - begin
		// for poster name
		$temp=$db->selectObject("user","id = " . $item->poster);
		$item->poster_name = "";
		if ($temp)
		{
			$item->poster_name = $temp-> firstname ." ". $temp->lastname;
		}                                       

		// for image
		//Get the image file if there is one.
		if (isset($item->file_id) && $item->file_id > 0) {
			$file = $db->selectObject('file', 'id='.$item->file_id);
			$item->image_path = BASE_URL . "/".$file->directory.'/'.$file->filename;
		}
		//Get the image file if there is one.
		if (isset($item->background_id) && $item->background_id > 0) {
			$file = $db->selectObject('file', 'id='.$item->background_id);
			$item->background_path ="/".$file->directory.'/'.$file->filename;
		}
		else $item->background_path="";
		
	}

	// Pull in RSS feeds. -RAM
	if (!empty($config->pull_rss)) {    
		if ($config->rss_cachetime != 3600) {
			define('MAGPIE_CACHE_AGE', $config->rss_cachetime);
		}
		$rssFeeds = array();
		$RSS = new rssfeed();
		foreach(unserialize($config->rss_feed) as $key=>$val) {
			$RSS->setURL($val);
			$rssFeeds[] = $RSS->fetch();
		}
		foreach ($rssFeeds as $feed) {
			foreach ($feed->items as $rssItem) {
				$rssObject = new stdClass();
				$rssObject->title = !empty($rssItem['title']) ? $rssItem['title'] : "";
				$rssObject->body = !empty($rssItem['description']) ? $rssItem['description'] : "";
				$rssObject->approved = 1;
				$rssObject->rss_link = !empty($rssItem['link']) ? $rssItem['link'] : "";
				$rssObject->posted = !empty($rssItem['date_timestamp']) ? $rssItem['date_timestamp'] : "";
				$rssObject->edited = !empty($rssItem['date_timestamp']) ? $rssItem['date_timestamp'] : "";
				$rssObject->published = !empty($rssItem['date_timestamp']) ? $rssItem['date_timestamp'] : "";
				$rssObject->isRss = true;
				$news[] = $rssObject;
			}
		}
	}

	switch($config->sortfield) {
		case "posted":
			$field = "Posted";
			break;
		case "publish":
			$field = "Posted";
			break;
		case "edited":
			$field = "Edited";
			break;
		default:
			$field = "Posted";
			break;
	}

	if ($config->sortorder == "ASC") {
		$order = "Ascending";
	} else {
		$order = "Descending";
	}

	$sortFunc = 'exponent_sorting_by'.$field.$order;

	if (!defined('SYS_SORTING')) require_once(BASE.'subsystems/sorting.php');
	usort($news,$sortFunc);
	usort($featured,$sortFunc);
	$news = array_slice($news, 0, $config->item_limit);
	// EVIL WORKFLOW
	$in_approval = $db->countObjects('newsitem_wf_info',"location_data='".serialize($loc)."'");
	$template->assign('canview_approval_link',$canviewapproval);
	$template->assign('in_approval',$in_approval);
	if($config->group_by_tags == true) {$template->assign('news',$grouped_news);} else {$template->assign('news',$news);}


	// pagination
	$template->assign('enable_pagination', $config->enable_pagination);
	$template->assign('total_news', $total);
	$template->assign('item_limit', $config->item_limit);
	$template->assign('pages',$page_count);
	$template->assign('page',$page);
	
	$template->assign('tag_collections', ($db->selectObjectsInArray('tag_collections', unserialize($config->collections))));
	$template->assign('featured', $featured);
	$template->assign('config', $config);        
	$template->assign('morenews',count($news) < $db->countObjects('newsitem',"location_data='" . serialize($loc) . "' AND (publish = 0 or publish <= " . time() . ') AND (unpublish = 0 or unpublish > ' . time() . ') AND approved != 0'));
	//Oct 14, 2010 - immanuel192   - Fix bug flow set cause loop forever - begin
	// Change if clase here, only check that flow_has_set has check or not
	if (!isset($_REQUEST['flow_has_set']))
		exponent_flow_set(SYS_FLOW_PUBLIC,SYS_FLOW_ACTION);
	//Oct 14, 2010 - immanuel192   - Fix bug flow set cause loop forever - end
	// Feb 12, 2011 - trungdt - set page title - begin
	$page_title=exponent_lang_getText("news_view_page_title");
	if ($page >1)
	{
		$page_title.=" - ".exponent_lang_getText("page")." ".$page;
	}
	$page_title.=" - ".SITE_TITLE;
	_ab_theme_action_register_title($page_title);
	// Feb 12, 2011 - trungdt - set page title - end
	$template->output();
?>